<template>
  <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
                     :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
                     :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex"
                     :sub-form-row-id="subFormRowId"
                     :in-table-flag="inTableFlag"
                     :column-prop="columnProp"
  >

    <div :class="{'readonly-mode-rich-editor': isReadMode}">
      <div style="border: 1px solid #ccc">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="fieldModel"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
        />
      </div>
    </div>

  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import i18n, {translate} from "@/utils/i18n";
import {convertFileIdToFileObj, deepClone} from "@/utils/util";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";

import {Toolbar, Editor} from "@wangeditor/editor-for-vue";
import '@wangeditor/editor/dist/css/style.css'

import request from "@/api";

export default {
  name: "rich-editor-widget",
  setup(props, context) {
    if (props.designState) {
    }
    const editorRef = shallowRef()
    const toolbarConfig = {
      insertKeys: {
        index: 23, // 自定义插入的位置
        keys: ['uploadAttachment'], // “上传附件”菜单
      },
      excludeKeys: [
        'group-video'
      ]
    }
    //上传方法，图片和附件的传参位置不同
    const customUpload = (type) => {
      return async (file, insertFn) => {
        let formData = window.rawWindow ? new window.rawWindow.FormData() : new FormData()
        formData.append('file', file)
        request.post(props.field.options.uploadURL,formData,{
          headers: {
            'Content-Type': 'multipart/form-data'
          },
        }).then(async res => {
          const fileObj = await convertFileIdToFileObj(props.field.options.uploadURL, res.data)
          type === 'image' ? insertFn(fileObj.url, fileObj.name, fileObj.url) : insertFn(fileObj.name, fileObj.url, fileObj.url,)
        })
      }
    }
    const editorConfig = {
      placeholder: '请输入内容...',
      hoverbarKeys: {
        attachment: {
          menuKeys: ['downloadAttachment'], // “下载附件”菜单
        },
      },
      MENU_CONF: {
        uploadImage: {
          // async customUpload(file, insertFn) {
          //   return customUpload('image')
          // }
          customUpload: customUpload('image')
        },
        uploadAttachment: {
          customUpload: customUpload('file')
        }
      }
    }
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })
    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
      // console.log('editorRef', editorRef.value)
    }
    return {
      editorRef,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  },
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },

  },
  components: {
    Toolbar,
    FormItemWrapper,
    Editor
    // quillEditor,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],

      customToolbar: [], //富文本编辑器自定义工具栏
      valueChangedFlag: false, //vue2-editor数据值是否改变标志
    }
  },
  /*computed: {
    editorOption() {
      return {
        placeholder: this.field.options.placeholder,
        modules: {
          //toolbar: this.customToolbar
        }
      }
    },

  },*/
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    this.registerToRefList()
    this.initFieldModel()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()
  },

  mounted() {
    this.handleOnMounted()
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {
    handleRichEditorChangeEvent() {
      this.valueChangedFlag = true
      this.syncUpdateFormModel(this.fieldModel)
    },

    handleRichEditorFocusEvent() {
      this.oldFieldValue = deepClone(this.fieldModel)
    },

    handleRichEditorBlurEvent() {
      if (this.valueChangedFlag) {
        this.emitFieldDataChange(this.fieldModel, this.oldFieldValue)
        this.valueChangedFlag = false
      }
    },

  }
}
</script>

<style lang="scss" scoped>
 /* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}

.readonly-mode-rich-editor {
  width: 100%; //解决垂直滚动条不居右显示的问题！！

  :deep(.ql-toolbar) {
    display: none;
  }

  :deep(.ql-container) {
    //border-top: 1px solid #cccccc !important;
    border: 0;
  }
}

</style>
